from PySide6.QtWidgets import QDialog,QMessageBox
from PySide6.QtCore import QDate
from sqlalchemy.orm import Session
import datetime

from views.book.books.operationbook import Ui_operationbook
from views.book.mode.book import Author, Publisher, Category, Books
from settings.publicvar import engine
from settings.initsetting.mode.initsetting import InitSetting
from views.schoolInfo.model.SchoolInfo import SchoolInfo


class OperationBookView(QDialog,Ui_operationbook):
    def __init__(self,is_state,data):
        super().__init__()
        self.setupUi(self)
        self.if_status(is_state)
        self.setFormStructure(data)

        self.changebtn.clicked.connect(self.changeFun)
        self.deletebtn.clicked.connect(self.deleteFun)
        self.addbtn.clicked.connect(self.addFun)
        self.resetbtn.clicked.connect(self.resetFun)

    def if_status(self,is_state):
        if is_state == 'view':
            self.titlelable.setText('查看图书信息')
            self.addbtn.hide()
            self.deletebtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        elif is_state == 'change':
            self.titlelable.setText('修改图书信息')
            self.addbtn.hide()
            self.deletebtn.hide()
        elif is_state == 'delete':
            self.titlelable.setText('删除图书信息')
            self.addbtn.hide()
            self.changebtn.hide()
            self.resetbtn.hide()
        else:
            self.deletebtn.hide()
            self.changebtn.hide()

    # 表单设置
    def setFormStructure(self,data):
        if data:
            self.idx.setText(str(data[0]))
            self.isbn.setText(data[1])
            self.title.setText(data[2])
            self.author.addItem(data[3])
            self.author.setCurrentText(data[3])
            self.publisher.addItem(data[4])
            self.publisher.setCurrentText(data[4])
            date = QDate.fromString(data[5], "yyyy-MM-dd")
            if date.isValid():
                self.publish_date.setDate(date)
            else:
                self.publish_date.setDate(QDate(1, 1, 1))
                self.publish_date.setSpecialValueText("请选择日期")
            self.summary.setText(data[6])
            self.price.setSpecialValueText(data[7])
            self.amount.setSpecialValueText(data[8])
            self.category.addItem(data[9])
            self.category.setCurrentText(data[9])
            date = QDate.fromString(data[10], "yyyy-MM-dd")
            if date.isValid():
                self.create_date.setDate(date)
            else:
                self.create_date.setDate(QDate(1, 1, 1))
                self.create_date.setSpecialValueText("请选择日期")
            self.mark.setText(data[12])

    # 获取数据
    def getFormData(self):
        idx = self.idx.text().strip()
        isbn = self.isbn.text().strip()
        title = self.title.text().strip()
        author = self.author.currentText()
        publisher = self.publisher.currentText()
        publish_date = self.publish_date.date()
        publish_date = datetime.date(publish_date.year(),publish_date.month(),publish_date.day())
        summary = self.summary.text().strip()
        price = self.price.value()
        amount = self.amount.value()
        category = self.category.currentText()
        create_date = self.create_date.date()
        create_date = datetime.date(create_date.year(), create_date.month(), create_date.day())
        mark = self.mark.text()
        update_date = datetime.datetime.now().date()

        # 作者
        with Session(engine) as session,session.begin():
            try:
                session.query(Author.id).filter(Author.name==author).one()
            except:
                author_tem = Author(name=author)
                session.add(author_tem)
        with Session(engine) as session,session.begin():
            author_id = session.query(Author.id).filter(Author.name==author).one()[0]
        # 出版社
        with Session(engine) as session,session.begin():
            try:
                session.query(Publisher.id).filter(Publisher.name==publisher).one()
            except:
                publisher_tem = Publisher(name=publisher)
                session.add(publisher_tem)
        with Session(engine) as session, session.begin():
            publisher_id = session.query(Publisher.id).filter(Publisher.name == publisher).one()[0]
        # 分类
        with Session(engine) as session,session.begin():
            try:
                session.query(Category.id).filter(Category.name==category).one()
            except:
                category_tem = Category(name=category)
                session.add(category_tem)
        with Session(engine) as session, session.begin():
            category_id = session.query(Category.id).filter(Category.name == category).one()[0]

        data = {'isbn':isbn,'title':title,'publish_date':publish_date,'summary':summary,'price':price,'amount':amount,'create_date':create_date,
                'update_date':update_date,'mark':mark,'author_id':author_id,'publisher_id':publisher_id,'category_id':category_id}
        print(data,'data')
        if idx != '':
            return [idx,data]
        else:
            return [False,data]

    def changeFun(self):
        data = self.getFormData()
        with Session(engine) as session,session.begin():
            init_school_id = session.query(InitSetting).one()
            data[1]['school_id'] = init_school_id.school_id
            session.query(Books).filter(Books.id == data[0]).update(data[1])
            self.author.addItem(self.author.currentText())
            QMessageBox.information(None,'','修改%s成功'%self.title.text())
            self.close()

    def deleteFun(self):
        data = self.getFormData()
        with Session(engine) as session, session.begin():
            session.query(Books).filter(Books.id == data[0]).delete()
            QMessageBox.information(None, '', '删除%s成功' % self.title.text())
            self.close()

    def addFun(self):
        data = self.getFormData()
        if not data[0]:
            with Session(engine) as session, session.begin():
                init_school_id = session.query(InitSetting).one()
                data[1]['school_id'] = init_school_id.school_id
                book = Books(**data[1])
                session.add(book)
                QMessageBox.information(None, '', '添加%s成功' % self.title.text())
                self.close()

    def resetFun(self):
        self.isbn.setText('')
        self.title.setText('')
        self.author.addItem('')
        self.author.setCurrentText('')
        self.publisher.addItem('')
        self.publisher.setCurrentText('')
        self.publish_date.setDate(QDate(1, 1, 1))
        self.publish_date.setSpecialValueText("请选择日期")
        self.summary.setText('')
        self.price.setSpecialValueText('')
        self.amount.setSpecialValueText('')
        self.category.setCurrentText('')
        self.create_date.setDate(QDate(1, 1, 1))
        self.create_date.setSpecialValueText("请选择日期")
        self.mark.setText('')

